import socket
import logging
import time

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('Test')

def test_sip_connection():
    """测试SIP连接"""
    logger.info("测试SIP服务器连接...")
    
    try:
        # 创建UDP socket
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.settimeout(5)
        
        # 尝试连接SIP服务器
        server_addr = ('101.126.17.13', 8116)
        test_message = "OPTIONS sip:101.126.17.13 SIP/2.0\r\nVia: SIP/2.0/UDP 192.168.31.104:5060\r\nFrom: <sip:test@192.168.31.104>\r\nTo: <sip:test@101.126.17.13>\r\nCall-ID: test123\r\nCSeq: 1 OPTIONS\r\nContent-Length: 0\r\n\r\n"
        
        sock.sendto(test_message.encode(), server_addr)
        
        # 尝试接收响应
        try:
            data, addr = sock.recvfrom(1024)
            logger.info(f"从服务器收到响应: {data.decode()}")
        except socket.timeout:
            logger.warning("未收到响应，但连接可能仍然有效")
        
    except Exception as e:
        logger.error(f"连接测试失败: {str(e)}")
    finally:
        sock.close()

if __name__ == "__main__":
    test_sip_connection()